const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
    // SA analyser 服务代理 - 必须在 /api 之前，因为它更具体
    app.use(
        '/api/sa',
        createProxyMiddleware({
            target: 'http://localhost:8091',
            changeOrigin: true,
            // 不需要 pathRewrite，因为 context '/api/sa' 会被自动移除
            // 然后我们需要手动添加 /sa 前缀
            pathRewrite: function (path, req) {
                // path 已经是 /scanLog/pageQuery (context /api/sa 被移除了)
                // 我们需要添加 /sa 前缀
                const newPath = '/sa' + path;
                console.log('[SA Proxy] Path rewrite:', path, '->', newPath);
                return newPath;
            },
            onProxyReq: (proxyReq, req, res) => {
                console.log('[SA Proxy] 请求:', req.method, req.url, '-> http://localhost:8091' + proxyReq.path);
            },
            onProxyRes: (proxyRes, req, res) => {
                console.log('[SA Proxy] 响应:', req.url, '状态码:', proxyRes.statusCode);
            },
            onError: (err, req, res) => {
                console.error('[SA Proxy] 错误:', req.url, err.message);
            }
        })
    );

    // 主服务代理
    app.use(
        '/api',
        createProxyMiddleware({
            target: 'http://localhost:8092',
            changeOrigin: true,
            onProxyReq: (proxyReq, req, res) => {
                console.log('[Main Proxy] 请求:', req.method, req.url, '-> http://localhost:8092' + proxyReq.path);
            },
        })
    );
}; 
